package com.zyx.javademo.collection.set;

import com.zyx.javademo.bean.User;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zyx
 * @since 2021/6/17 21:42
 * desc: TreeSet案例
 */
public class TreeSetDemo {
    public static void main(String[] args) {
        // intTreeSet();
        userTreesetDemo();
    }

    public static void intTreeSet() {
        List<Integer> list = Arrays.asList(1, 9, 7, 8, 3, 2, 5);
        TreeSet<Integer> set = new TreeSet<>(list);
        set.add(18);
        set.pollLast();
        System.out.println(set);
    }

    private static void userTreesetDemo() {
        User user1 = new User("zhangsan", 21, new BigDecimal(180));
        User user2 = new User("lisi", 20, new BigDecimal(180));
        User user3 = new User("wangwu", 14, new BigDecimal(180));
        User user4 = new User("zhaoliu", 13, new BigDecimal(180));
        User user5 = new User("tianqi", 25, new BigDecimal(180));
        User user6 = new User("wangba", 21, new BigDecimal(180));
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        userList.add(user6);
        TreeSet<User> userSet = new TreeSet<>(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                int res = Integer.compare(o1.getAge(), o2.getAge());
                return res;
            }
        });
        for (User user : userList) {
            userSet.add(user);
            if (userSet.size() > 4) {
                userSet.pollLast();
            }
        }
        System.out.println(userSet);
    }
}
